const path = require("path")
const fs = require("fs")

const dir = new fs.Stats()

const scanner = (dir, pattern, opts = {}) => {
  let {handler, deep = false, context} = opts
  let stat
  try {
    stat = fs.statSync(dir)
    if (!stat.isDirectory()) {
      throw new Error(`${dir.toString()} 不是一个文件夹`)
    }
  } catch (e) {
    console.log(e.toString())
    process.exit(1)
  }

  const files = fs.readdirSync(dir).map(item => path.resolve(dir, item))
  files.forEach(file => {
    if (fs.statSync(file).isDirectory()) {
      deep && scanner(file, pattern, opts)
    } else {
      const isMatch = pattern.test(file)
      if (isMatch && handler) {
        handler(file)
      }
    }
  })
}

module.exports = scanner













